from uliweb.orm import *
from uliweb.core import dispatch
import os

import datetime

User = get_model('user')

class Category(Model):
    name = Field(str, max_length=255, required=True)
    documents_count = Field(int, default=0)
    
def new_category(name):
    return Category(name=name).save()

class Document(Model):
    filename = Field(str, max_length=255, required=True)
    description = Field(TEXT)
    category = Reference(Category, collection_name='category_documents')
    owner = Reference(User, collection_name='user_documents')
    create_time = Field(datetime.datetime, auto_now_add=True)
    size = Field(int, default=0)
    
def upload_document(fileobj, description, category_id, user, basepath):
    from uliweb.contrib.upload import save_file_field, get_filename, normfilename

    c = Category.get(int(category_id))
    
    path = normfilename(os.path.join(basepath, c.name, fileobj.data.filename))
    
    filename = save_file_field(fileobj, filename=path)
    c.documents_count += 1
    c.save()
    
    rfile = get_filename(filename, filesystem=True)
    d = Document(filename=filename, description=description, category=c, owner=user,
        size=os.path.getsize(rfile)).save()
        
    return d

def delete_document(document_id):
    from uliweb.contrib.upload import delete_filename
    doc = Document.get(int(document_id))
    filename = doc.filename
    
    c = doc.category
    c.documents_count -= 1
    c.save()
    
    _id = doc.id
    doc.delete()
    
    delete_filename(filename)
    return _id

def edit_document(doc, description, category_id, user, basepath):
    from uliweb.contrib.upload import get_filename, normfilename

    changed = False
    description = description.strip()
    if doc.description.strip() != description:
        changed = True
        doc.description = description
    
    c_id = Document.category.get_value_for_datastore(doc)
    category_id = int(category_id)
    if c_id != category_id:
        changed = True
        
        old_c = Category.get(c_id)
        old_c.documents_count -= 1
        old_c.save()
        
        c = Category.get(category_id)
        c.documents_count += 1
        c.save()
        
        doc.category = c
        
        old_filename = doc.filename
        filename = normfilename(os.path.join(basepath, c.name, os.path.basename(old_filename)))
        
        if old_filename != filename:
            os.rename(get_filename(old_filename, filesystem=True), get_filename(filename, filesystem=True))
            
    if changed:
        doc.save()
        
    return changed